package com.yunlongn.common.core.autowired;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.annotation.InjectionMetadata;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 抽象的自动注入方法
 * @author yunlgongn
 */
public abstract class AbstractAnnotationBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    private final Set<Class<? extends Annotation>> annotationTypes = new LinkedHashSet<>(4);

    private final Map<String, InjectionMetadata> injectionMetadataCache = new ConcurrentHashMap<>(256);

    protected final Log logger = LogFactory.getLog(getClass());

    /**
     * 处理的 annotationType 对象
     * @return Annotation 自定义注解
     */
    public abstract Class<? extends Annotation> annotationType();

    AbstractAnnotationBeanPostProcessor () {
        Class<? extends Annotation> annotation = this.annotationType();
        annotationTypes.add(annotation);
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
        InjectionMetadata metadata = findAbstractMetadata(beanName, bean.getClass(), pvs);
        try {
            // 注入数据
            metadata.inject(bean, beanName, pvs);
        }
        catch (BeanCreationException ex) {
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
        }
        return pvs;
    }

    private InjectionMetadata findAbstractMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
        String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        // 获取是否已经读取过这个 class 类的 InjectionMetadata 有的话直接从缓存中获取出去
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            synchronized (this.injectionMetadataCache) {
                // 双重检查
                metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                    if (metadata != null) {
                        metadata.clear(pvs);
                    }
                    metadata = buildAbstractMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }

    private InjectionMetadata buildAbstractMetadata(final Class<?> clazz) {
        if (!AnnotationUtils.isCandidateClass(clazz, this.annotationTypes)) {
            return InjectionMetadata.EMPTY;
        }

        List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
            // 循环 targetClass 的所有 field 并执 FieldCallback 逻辑 （函数式编程接口，传入的是一个执行函数）
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                // 获得字段上面的 Annotation 注解
                MergedAnnotation<?> ann = findAbstractAnnotation(field);
                if (ann != null) {
                    // 判断是否为静态属性 如果是，则不进行注入
                    if (Modifier.isStatic(field.getModifiers())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Abstract annotation is not supported on static fields: " + field);
                        }
                        return;
                    }
                    currElements.add(new AbstractFieldElement(field, ann));
                }
            });
            //数据加到数组最前方 父类的的注解都放在靠前的位置
            elements.addAll(0, currElements);
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);

        return InjectionMetadata.forElements(elements, clazz);
    }

    @Nullable
    private MergedAnnotation<?> findAbstractAnnotation(AccessibleObject ao) {
        // 将指定方法上的注解合并成一个注解
        MergedAnnotations annotations = MergedAnnotations.from(ao);
        // 循环要扫描的注解 annotationTypes 那个在前面就认哪个
        for (Class<? extends Annotation> type : this.annotationTypes) {
            MergedAnnotation<?> annotation = annotations.get(type);
            if (annotation.isPresent()) {
                return annotation;
            }
        }
        return null;
    }

    @Deprecated
    @Override
    public PropertyValues postProcessPropertyValues(
            PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) {

        return postProcessProperties(pvs, bean, beanName);
    }


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    /**
     * 实现交给子类进行实现 将注解透传出去
     * @param mergedAnnotation 属性上的注解
     * @param bean bean实例
     * @param beanName bean的名字
     * @param field 字段
     * @param autowiredFieldElement 注解
     * @return 注入对象
     * @throws Exception
     */
    protected abstract Object getInjectedObject(MergedAnnotation<?> mergedAnnotation, Object bean, String beanName, Field field,
                                                AbstractFieldElement autowiredFieldElement) throws Exception;


    public class AbstractFieldElement extends InjectionMetadata.InjectedElement {

        private final MergedAnnotation<?> mergedAnnotation;

        public AbstractFieldElement(Field field, MergedAnnotation<?> mergedAnnotation) {
            super(field, null);
            this.mergedAnnotation = mergedAnnotation;
        }

        @Override
        protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
            Field field = (Field) this.member;
            Object value = getInjectedObject(this.mergedAnnotation, bean, beanName, field, this);
            if (value != null) {
                ReflectionUtils.makeAccessible(field);
                field.set(bean, value);
            }
        }

    }

}
